package org.shj.basic;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

import org.shj.util.Util;

public class SemaphoreDemo {

	private static final int THREAD_COUNT = 30;
	private static ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT);
	
	private static Semaphore s = new Semaphore(10); //只允许有10个通行证
	
	public static void main(String[] args){
		for(int i = 0 ; i < THREAD_COUNT; i++){
			int ind = i;
			executor.execute(new Runnable(){
				public void run(){
					try{
						s.acquire();//如果已经有10个线程获得了通行证，则当前线程会被阻塞，直到其它线程释放通行证
						System.out.println(ind + " save data");
						Util.sleep(1);
						s.release();
					}catch(Exception e){
						
					}
				}
			});
		}
		executor.shutdown();
	}
}
